<?php

namespace app\api\service;

use app\api\utils\JWT;
use app\lib\exception\BaseException;
use think\Request;

class Login
{
    public static function login($username, $password, $source)
    {
        define("URL", config('const.verify_url'));
        $ch = curl_init();
        $post_data["user"] = $username;
        $post_data["password"] = $password;
        curl_setopt($ch, CURLOPT_URL,URL);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $output = curl_exec($ch);
        curl_close($ch);
        $result = json_decode($output, true);
        if($result == 0 || $result == 1 || $result == 2){
            throw new BaseException([
                'msg' => '账号或密码错误',
                'code' => 9527,
                'errorCode' => 400
            ]);
        }else {
            if (isset($result['user_name']) && isset($result['access'][config('const.project_name').'-'.$source])) {
                $payload = array(
                    "role" => $source,
                    "permission" => array_keys($result['access']),
                    "name" => $result['user_name'],
                    "username" => $username,
                    "userid" => $result['user_id'],
                    'iat'=>time(),
                    'exp'=>time() + (config('const.expires_time') * 1 == -1?(10*365*24*3600):(config('const.expires_time') * 1))
                );
                $sign = JWT::getToken($payload);
                return [
                    'token' => $sign['data']['token'],
                    "role" => $source,
                    "username" => $username,
                    'name' => $result['user_name']
                ];
            }else{
                throw new BaseException([
                    'msg' => '用户没有权限',
                    'code' => 9527,
                    'errorCode' => 400
                ]);
            }
        }
    }

    public static function checkToken(){
        $token = Request::instance()->header('token');
        if(empty($token) ){
            throw new BaseException([
                'msg' => '登陆已过期,请重新登陆',
                'code' => 9527,
                'errorCode' => 403
            ]);
        }
        $result = JWT::verifyToken($token);
        if($result['status'] != 1){
            throw new BaseException([
                'msg' => '登陆已过期,请重新登陆',
                'code' => 9527,
                'errorCode' => 403
            ]);
        }
        if(!in_array(config('const.project_name').'-'.$result['data']['role'], $result['data']['permission'])){
            throw new BaseException([
                'msg' => '暂无权限',
                'code' => 9527,
                'errorCode' => 403
            ]);
        }
    }
}